<template>
  <el-card style="width: 100%" shadow="never" class="many-attribute">
    <template #header>
      <div class="card-header">
        <span>多属性信息</span>
      </div>
    </template>
    <el-tabs v-model="activeName" class="demo-tabs" style="width: 100%">
      <el-tab-pane label="多属性信息" name="first">
        <div
          class="but-group"
          style="display: flex; flex-direction: row; justify-content: flex-end; margin-bottom: 20px"
        >
          <el-button type="primary" @click="selectAttributeHandler">添加SKU</el-button>
        </div>
        <el-table border :data="tableData">
          <el-table-column prop="imageUrl" label="属性图" width="100" align="center">
            <template #default="scoped">
              <el-upload
                class="avatar-uploader"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                :show-file-list="false"
                :on-success="(ev) => handleAvatarSuccess(ev, scoped.rows)"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="scoped.imageUrl" :src="scoped.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) of dynamicsTableCol"
            :key="index"
            :prop="item.value"
            :label="item.label"
             width="100"
          ></el-table-column>
          <el-table-column prop="sku" label="sku编码" width="160">
            <template #default="scoped">
              <el-input v-model="scoped.row.sku" placeholder="请输入sku编码"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="nameCn" label="中文标题" width="160">
            <template #default="scoped">
              <el-input v-model="scoped.row.nameCn" placeholder="请输入中文标题"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="nameEn" label="英文标题" width="160">
            <template #default="scoped">
              <el-input v-model="scoped.row.nameEn" placeholder="请输入英文标题"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="币种" width="160">
            <template #default="scoped">
              <el-select v-model="scoped.row.currency" placeholder="请选择币种" clearable style="width: 100%">
              <el-option label="人民币" value="CNY"></el-option>
              <el-option label="美元" value="USD"></el-option>
              <el-option label="越南盾" value="VND"></el-option>
              <el-option label="泰铢" value="THB"></el-option>
              <el-option label="马来西亚币" value="MYR"></el-option>
              <el-option label="菲律宾比索" value="PHP"></el-option>
            </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="costPrice" label="成本价" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.costPrice" placeholder="请输入成本价"></el-input>
            </template>
          </el-table-column>
         
          <el-table-column prop="length" label="长度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.length" placeholder="请输入长度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="width" label="宽度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.width" placeholder="请输入宽度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="height" label="高度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.height" placeholder="请输入高度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.weight" placeholder="请输入重量">
                <template #append>g</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="packLength" label="包装长度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.packLength" placeholder="请输入包装长度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="packWidth" label="包装宽度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.packWidth" placeholder="请输入包装宽度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="packHeight" label="包装高度" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.packHeight" placeholder="请输入包装高度">
                <template #append>mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="packWeight" label="包装重量" width="160">
             <template #default="scoped">
              <el-input v-model="scoped.row.packWeight" placeholder="请输入包装重量">
                <template #append>g</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button type="primary" @click="submitHandler">提交</el-button>
    </div>
    <!-- 多属性弹框开始 -->
    <el-dialog v-model="dialogVisible" title="选择多属性" width="500" :before-close="handleClose">
      <div v-for="(item, key) in skuAttributeGroup" :key="key">
        <div style="margin: 10px 0">{{ key }}</div>
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="(it, index) of item"
            :key="index"
            :label="it.attributeValueId"
            :value="it.attributeValueId"
            >{{ it.attributeValueName }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelHandler">取消</el-button>
          <el-button type="primary" @click="confirmHandler"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 多属性弹框结束 -->
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch,defineProps } from 'vue';
import { groupBy, cloneDeep } from 'lodash';
import {ElMessage} from 'element-plus';
import {skuData,tableDataList} from './data';
const activeName = ref('first');
const dialogVisible = ref(false);

const props = defineProps({
  id:{
    type: String,
    default:'1',
  },
  categoryId:{
    type: String,
   default:'1',
  }
})
const handleClose = () => {
  dialogVisible.value = false;
};
const selectAttributeHandler = async () => {
  await initSkuAttribute();
  dialogVisible.value = true;
};
// sku属性分组
const skuAttributeGroup = ref({});
const skuAttributeOriginData = ref([]);
const checkList = ref([]); // 新的选中的
const oldCheckList = ref([]); // 旧的选中的
const initSkuAttribute = async () => {
  const groupMap = groupBy(skuData.rows, 'attributeName');
  skuAttributeGroup.value = groupMap;
  skuAttributeOriginData.value = skuData.rows;
};
const cancelHandler = () => {
  dialogVisible.value = false;
  checkList.value = [];
  oldCheckList.value = [];
};
// 关闭弹框
const checkSkuAttribute = ref([]); // 当前选中的
const dynamicsTableCol = ref([]); // 动态表格的列
const checkSkuAttributeList = ref([]);
const skuPrefix = ref(''); // 本次请求sku前缀
const maxSkuIndex = ref(''); // 当前返回最大的skuIndex
const tableData = ref([]);
const tableMap = {};
const confirmHandler = () => {
  checkSkuAttribute.value = skuAttributeOriginData.value.filter((item) =>
    checkList.value.includes(item.attributeValueId)
  ).sort((a,b)=>a.sort - b.sort);
  const attributeNameGroupData = Object.keys(groupBy(checkSkuAttribute.value, 'attributeName'));
  dynamicsTableCol.value = [];
  for (const key of attributeNameGroupData) {
    dynamicsTableCol.value.push({
      label: key,
      value: key,
    });
  }
  checkSkuAttributeList.value = Object.values(groupBy(checkSkuAttribute.value, 'attributeName'));
  dialogVisible.value = false;
  // 根据checkSkuAttribute.value的数据用笛卡尔积生成表格行
};

const generateSku = (skuAttribute) => {
  console.log(JSON.stringify(skuAttribute), '监听数据', skuAttribute.length);
  if (skuAttribute.length == 0) {
    tableData.value = [];
    return;
  }
  // 循环组成sku数据
  let skuList = [];
  if(skuAttribute.length > 1) {
    skuList= skuAttribute.reduce((pre, cur) => {
      let res = [];
      for (const item of pre) {
        for (const it of cur) {
          res.push({
            [item.attributeName]:item.attributeValueName,
            [it.attributeName]:it.attributeValueName,
            [item.attributeName]: item.attributeValueName,
            [it.attributeName]: it.attributeValueName,
            attrIdList:[item.attributeValueId,it.attributeValueId]
          });
        }
      }
      return res;
    })
    .map((it) => {
      // const oldData = afterSku.value.find((item) => item.attributeValue == it.attributeValue);
      return {
        ...it,
        // id: oldData ? oldData.id : '',
        // [tableMap[it.attributeName]]:it.attributeValueName,
        sku:'',
        nameCn: '',
        nameEn: '',
        currency: '',
        costPrice: '',
        length: '',
        width: '',
        height: '',
        weight: '',
        packLength: '',
        packWidth: '',
        packHeight: '',
        packWeight: '',
      };
    });
  } else {
    skuList = skuAttribute[0].map(item => {
      return {
        ...item,
        [item.attributeName]:item.attributeValueName,
        attrIdList:[item.attributeValueId],
        sku:'',
        nameCn: '',
        nameEn: '',
        currency: '',
        costPrice: '',
        length: '',
        width: '',
        height: '',
        weight: '',
        packLength: '',
        packWidth: '',
        packHeight: '',
        packWeight: '',
      }
    })
  }
  console.log(JSON.stringify(skuList), '组装新的数据');
  console.log(JSON.stringify(tableData.value), '当前表格数据');
  // 判断避免重复添加
  if (skuList.length ==0){
    tableData.value = [];
    return;
  }
  const newSkuList = skuList.map(item => {
    return {
      ...item,
      attrIdListStr:item.attrIdList.sort((a,b)=>a-b).join('-'),
    }
  })
  // 判断是新的skuList是否要新增到表格中还是要从表格中删除
  const newSkuAttrIdListStrMap = {};
  for (const item of newSkuList) {
    newSkuAttrIdListStrMap[item.attrIdListStr] = item;
  }
  console.log(newSkuAttrIdListStrMap,'新的map')
  const tableAttrIdListStrMap = {};
  for(const item of tableData.value) {
    tableAttrIdListStrMap[item.attrIdListStr] = item;
  }
  console.log(tableAttrIdListStrMap,'表格map')
  const newTableData = [];
  // 复制之前的存在的
  for (const tableItem of tableData.value) {
    if (newSkuAttrIdListStrMap[tableItem.attrIdListStr]) {
      newTableData.push(tableItem);
    } 
  }
  // 处理本次要添加的
  for (const skuItem of newSkuList) {
    if (!tableAttrIdListStrMap[skuItem.attrIdListStr]) {
      newTableData.push(skuItem);
    }
  }
  console.log(JSON.stringify(newTableData),'新表格数据')
  // 查询当前表格中最大的sku
  tableData.value = newTableData.map((item,index) => {
    if (!item.sku) {
      let sku = '';
      if (newTableData.length) {
        const skuIndex = newTableData.map(it1 =>{
          if (it1.sku) {
            return it1.sku.substring(it1.sku.lastIndexOf('-')+1)
          } else {
            return maxSkuIndex.value;
          }
        }).sort((a,b)=>b-a);
        sku = skuPrefix.value?`${skuPrefix.value}-${+skuIndex[0]+1+index}`:`${index+1}`;
      }
      return {
        ...item,
        sku
      }
    } else {
      return item;
    }
  })
};
// 监听选中的
watch(
  () => checkSkuAttributeList.value,
  (newValue) => {
    generateSku(cloneDeep(newValue));
  },
  {
    deep: true,
  }
);
// 监听sku表格的变化,并将当前sku进行备份
const afterSku = ref([]);
watch(
  () => tableData.value,
  (value) => {
    afterSku.value = cloneDeep(value);
  },
  { deep: true }
);

const handleAvatarSuccess = (response, uploadFile, rowData) => {
  console.log(rowData, response, uploadFile, '11111');
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只能上传jpeg、png');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传文件不能大于2MB!');
    return false;
  }
  return true;
};
// 初始化页面获取数据
const initSkuData = async (id) => {
  try {
    const data = tableDataList;
    tableData.value = data ?? [];
    // 处理动图表格列
    if (Array.isArray(data)&&data.length) {
      skuPrefix.value = data[0].sku.substring(0,data[0].sku.indexOf('-'));
      const skuList = data[0].productSkuAttributeValueDTOS.sort((a,b)=>a.sort-b.sort) ?? [];
      for (const sku of skuList) {
        dynamicsTableCol.value.push({
          label: sku.attributeName,
          value: sku.attributeName,
        });
      }
      // 表格中动态添加sku数据
      const newTableData  = [];
      const allSkuList = []
      for (const item of data) {
        // 动态给新表格中添加列
        for (const sku of item.productSkuAttributeValueDTOS) {
          item[tableMap[sku.attributeName]] =sku.attributeValueName;
          item[sku.attributeName] =sku.attributeValueName;
        }
        item.attrIdList = item.productSkuAttributeValueDTOS.map(it =>it.attributeValueId); // 添加属性id
        allSkuList.push(...item.productSkuAttributeValueDTOS);
        newTableData.push({
          ...item,
        });
        // 处理已经选择的sku
        checkList.value = [...new Set(allSkuList.map(item =>+item.attributeValueId))];
        
        
      }
      // 处理当前最大的skuIndex
      const skuIndexList = data.map(item =>{
        if (item.sku) {
          return +item.sku.substring(item.sku.lastIndexOf('-')+1,)
        } else {
          return 0;
        }
      }).sort((a,b)=>b-a);
      maxSkuIndex.value = skuIndexList ? skuIndexList[0]:0;
      tableData.value =newTableData.map(item => {
        return {
          ...item,
          attrIdListStr:item.attrIdList.sort((a,b)=>a-b).join('-'), // 为了记录更好比较
        }
      });
    }
  } catch(e) {
    tableData.value =  [];
  }
}
// 提交
const submitHandler = async () => {
  console.log(JSON.stringify(tableData.value),"提交数据");
  console.log(JSON.stringify(skuAttributeOriginData.value),"源sku数据")
  // 给表格数据添加productSkuAttributeValueDTOS属性
  if (!tableData.value.length) {
    Element.error('请补充表格数据');
    return
  }
  const postTableData = [];
  for (const item of tableData.value) {
    if (item.productSkuAttributeValueDTOS) {
      postTableData.push({
        ...item,
        skuId:item.id,
      });
    } else {
      // 拆分当前sku的值
      if (item.attrIdListStr) {
        const attrIdList = item.attrIdListStr.split('-').map(item =>+item);
        // 根据id去找skuAttributeOriginData 数据
        const productSkuAttributeValueDTOS = skuAttributeOriginData.value.filter(it => attrIdList.includes(it.attributeValueId)).map(it => {
          return {
            ...it,
            id:null,
          }
        });
        postTableData.push({
          ...item,
          spu:route.query.spu,
          spuId:props.id,
          skuId:null, 
          productSkuAttributeValueDTOS,
        })
      }
      
    }
  }
};
onMounted(() => {
  if (props.id) {
    initSkuData(props.id);
  }else {
    ElMessage.error('请保存基本信息');
    emits('changeTab');
  }
})
</script>
<style lang="scss">
.many-attribute {
  .footer {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    margin-top: 10px;
  }
  .avatar-uploader .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    text-align: center;
  }
}
</style>
